import json
import httpx
import asyncio
from dotenv import load_dotenv
import os
from icecream import ic
from models.model import Cities, init
from tortoise import Tortoise


load_dotenv()


APP_ID = os.getenv('APP_ID')
APP_KEY = os.getenv('APP_KEY')


async def text_to_telegram(data: json) -> str:
    current_weather = data['current_weather']
    local_now = data['local_now']
    range_weather = data['range_weather']
    ic('Tut1')
    message = f"🌍 Погода в {data['town']['loc_case_name']} (на {local_now}):\n"
    message += f"🌡 Температура: {current_weather['temperature']}°C (ощущается как {current_weather['temp_feels']}°C)\n"
    message += f"🌧 Состояние: {current_weather['description_text']}\n"
    message += "🔄 Погода на сегодня:\n"
    ic('Tut2')
    for period, details in current_weather['periods'].items():
        message += f"  - {period.capitalize()}: {details['temperature']}°C, {details['icon'].replace('-', ' ').title()}\n"
    ic('Tut3')
    message += "📅 Прогноз на ближайшие дни:\n"
    for forecast in range_weather:
        message += f"  {forecast['date']}: {forecast['forecast']['icon'].replace('-', ' ').title()}, "
        message += f"макс {forecast['forecast']['max_temperature']}°C, мин {forecast['forecast']['min_temperature']}°C, "
        message += f"осадки {forecast['forecast']['precipitation']}%, ветер {forecast['forecast']['wind_direction']} {forecast['forecast']['wind_speed']} м/с\n"
    ic(message)
    return message
    

async def url_connect(url: str, params: dict=None, cookies: dict=None, headers: dict=None) -> httpx.Response:
    async with httpx.AsyncClient() as client:
        response = await client.get(url, params=params, cookies=cookies, headers=headers)
        return response


async def geo_id(city: str) -> json:
    headers = {
        'accept': '*/*',
        'accept-language': 'ru-RU,ru;q=0.8',
        'origin': 'https://weather.rambler.ru',
        'priority': 'u=1, i',
        'referer': 'https://weather.rambler.ru/',
        'sec-ch-ua': '"Chromium";v="124", "Brave";v="124", "Not-A.Brand";v="99"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-site',
        'sec-gpc': '1',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
    }

    params = {
        's': city,
        'type': '50',
    }
    geo_id_pos = await url_connect('https://www.rambler.ru/location/geo_list/', params=params, headers=headers)
    geo_dict = {}
    for key, value in geo_id_pos.json().items():
        if 'Россия' in value['parents']:
            geo_dict[key] = value
    return ic(geo_dict)

async def coordinates(cities: str) -> str:
    id = await geo_id(cities)
    id = list(id.keys())[0]
    cookies = {
        'nearest_cities': 'no_icon',
        'ruid': 'vAsAAH5AMWaZN/cvAV8BAAB=',
        'adtech_uid': '4fbdbe48-933c-4182-ba36-b9b40621f069%3Arambler.ru',
        'top100_id': 't1.139601.694240409.1714503807425',
        'last_visit': '1714485807439%3A%3A1714503807439',
        'proto_uid': '1CIAAH9AMWbEeV81AQqynwB=',
        'dvr': 'gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA:1714503808',
        'lvr': '1714503808',
        'r_id_split': '3',
        't3_sid_139601': 's1.1487599146.1714503807427.1714503814744.1.13',
        't3_sid_7726560': 's1.800175778.1714503807438.1714503814745.1.9',
        't3_sid_7728281': 's1.2145734266.1714503807442.1714503814746.1.9',
    }

    headers = {
        'accept': '*/*',
        'accept-language': 'ru-RU,ru;q=0.8',
        # 'cookie': 'nearest_cities=no_icon; ruid=vAsAAH5AMWaZN/cvAV8BAAB=; adtech_uid=4fbdbe48-933c-4182-ba36-b9b40621f069%3Arambler.ru; top100_id=t1.139601.694240409.1714503807425; last_visit=1714485807439%3A%3A1714503807439; proto_uid=1CIAAH9AMWbEeV81AQqynwB=; dvr=gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA:1714503808; lvr=1714503808; r_id_split=3; t3_sid_139601=s1.1487599146.1714503807427.1714503814744.1.13; t3_sid_7726560=s1.800175778.1714503807438.1714503814745.1.9; t3_sid_7728281=s1.2145734266.1714503807442.1714503814746.1.9',
        'priority': 'u=1, i',
        'referer': 'https://weather.rambler.ru/',
        'sec-ch-ua': '"Chromium";v="124", "Brave";v="124", "Not-A.Brand";v="99"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'sec-gpc': '1',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
    }
    
    params = {
        'geo_id': id,
    }
    
    weather = await url_connect('https://weather.rambler.ru/api/v3/index/', params=params, cookies=cookies, headers=headers)
    # weather = await url_connect(f'http://127.0.0.1:8000/api-weather/', data={'city': ic(cities)}, auth=('kawr', '123'))
    text = await text_to_telegram(weather.json())
    return text




async def main1() -> None:
    await coordinates("Казань")
    
    
    
if __name__ == "__main__":
    asyncio.run(main1())